package com.blue.cat.handler.gpt;

import com.blue.cat.bean.vo.GptModelConfigVo;
import com.blue.cat.config.ChatBaseGPTProperties;
import com.blue.cat.handler.GptModelConfigManager;
import com.blue.cat.service.ChatBaseOpenAiProxyService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author huyd
 * @date 2023/5/23 8:09 PM
 */
@Slf4j
public class OpenAiProxyServiceFactory {

    private static final Map<String, List<ChatBaseOpenAiProxyService>> serviceMap = new ConcurrentHashMap<>();

    /**
     * 获取当前模型的服务类
     *
     * @param model
     * @param userId
     * @return
     */
    public static ChatBaseOpenAiProxyService createProxyService(String model, Long userId){
        List<ChatBaseOpenAiProxyService> proxyServices = serviceMap.get(model);
        if(CollectionUtils.isEmpty(proxyServices)){
            return null;
        }
        int i = (int) (userId % proxyServices.size());
        return proxyServices.get(i);
    }

    /**
     * 初始化gpt模型配置
     * @param gptModelConfigManager
     */
    public static void initGptModelConfig(GptModelConfigManager gptModelConfigManager){
        List<GptModelConfigVo> gptModelConfigVos = gptModelConfigManager.getAllValidGptConfig();
        log.info("gpt model config  init size={}",gptModelConfigVos.size());
        for (GptModelConfigVo gptModelConfigVo : gptModelConfigVos) {
            try {
                List<ChatBaseOpenAiProxyService> openAiProxyServiceList = serviceMap.get(gptModelConfigVo.getModel());
                if(CollectionUtils.isEmpty(openAiProxyServiceList)){
                    openAiProxyServiceList = new ArrayList<>();
                    serviceMap.put(gptModelConfigVo.getModel(),openAiProxyServiceList);
                }
                ChatBaseGPTProperties properties = new ChatBaseGPTProperties();
                properties.setChatModel(gptModelConfigVo.getModel());
                properties.setSessionExpirationTime(2);
                properties.setToken(gptModelConfigVo.getToken());
                properties.setBaseUrl(gptModelConfigVo.getBaseUrl());
                ChatBaseOpenAiProxyService openAiProxyService = new ChatBaseOpenAiProxyService(properties);
                openAiProxyServiceList.add(openAiProxyService);
            }catch (Exception e){
                // 在这里加上catch 防止初始化一个key有问题 从而影响其它的key了
                log.error("initGptModelConfig error gptModelConfigVo={}",gptModelConfigVo,e);
            }
        }
    }

    public static Map<String, List<ChatBaseOpenAiProxyService>> getServiceMap() {
        return serviceMap;
    }
}
